﻿using AppHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 私钥  用于生成注册码  请注释掉
        /// </summary>
        private const string privateKey = "gDOOuok04NHgreQ6rXXHKHA/wbHSaeWlk0F+qe6sDHBr2E/jIa5rpxhHReKKohObzP6hAKSgoMhON1hoXsznVWUG7PfA/dumVRxo6sgVxMjbw54N/iztZIjx0ALX1cPOng/kyh2Fnv0kRV0E/e6ZifYGDKJBXYWuUrOkhMkuFw4JyoyZtA9BFADbF3zpJEGnKz9oh5kONhIfOt2V8yPNu+4WVukY6jLZS+/jqy0IyBPlw9/yViP+DNBUkLztJOTAFOEINOlfIVEdmC20YyaHo8/fTMH3HbF9kfImmN8DJGGx72Sm2JpM73Rb4yvLYPGz0h9QFiFEn7he1mTZx5A4MTE=";
        /// <summary>
        /// 公钥  用于软件解密注册码 
        /// </summary>
        private const string publicKey = "AwEAAcqMmbQPQRQA2xd86SRBpys/aIeZDjYSHzrdlfMjzbvuFlbpGOoy2Uvv46stCMgT5cPf8lYj/gzQVJC87STkwBThCDTpXyFRHZgttGMmh6PP30zB9x2xfZHyJpjfAyRhse9kptiaTO90W+Mry2Dxs9IfUBYhRJ+4XtZk2ceQODEx";


        /// <summary>
        /// 私钥  用于生成注册码
        /// </summary>
        private const string privateKeyTime = "gAg1Wv4fcaef5mdeuSKI3iuyFGDW/wgBm0WNNzwZsWirvjGupTew06DLDCY222qmigjgLCibr8VwvxAor461w1iCOcCi0NQlb4WCiHNSefzRbS52mxsfBrJjc7mpdoKloyzfzo7Rx1OM2IxMiWyTZj5/dFoh1rsgaj98co2JuxKV4Y7HznT5WjkbSu9quJ7vbFSXA+eDYaNlxeAZCyfFAN//uT9RgVix7MBzM4XPbjsb88knegayFirGPgOeeQD42ErENdA+r6ZP4iC2+bFD0O7KoDqYrstsMNasKx+NYWTsZTKHD6rba9QCERpo5nLI8T+JA9t2psXnLG1Vi4W8xwE=";
        /// <summary>
        /// 公钥  用于软件解密注册码
        /// </summary>
        private const string publicKeyTime = "AwEAAeGOx850+Vo5G0rvarie72xUlwPng2GjZcXgGQsnxQDf/7k/UYFYsezAczOFz247G/PJJ3oGshYqxj4DnnkA+NhKxDXQPq+mT+IgtvmxQ9DuyqA6mK7LbDDWrCsfjWFk7GUyhw+q22vUAhEaaOZyyPE/iQPbdqbF5yxtVYuFvMcB";



        /// <summary>
        /// 注册窗口
        /// </summary>
        RegForm regForm = new RegForm();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {            
            regForm.license.publicKey = publicKey;
            regForm.license.privateKeyTime = privateKeyTime;
            regForm.license.publicKeyTime = publicKeyTime;

            textBox1.Text = regForm.license.GetMachineCode();
            dateTimePicker1.Value = DateTime.Now.AddHours(1);
            ////注册检测
            //if (!(regForm.ShowDialog() == DialogResult.OK))
            //{
            //    //程序未注册直接退出
            //    Close();
            //    Application.Exit();
            //    return;
            //}
            //else
            //{
            //    //启动加载等待
            //    //StartingWindow startingWindow = new StartingWindow("应用程序名称","公司名称");
            //    StartingWindow startingWindow = new StartingWindow("AppDemo", "dhsososo@163.com");
            //    startingWindow.loadingHandler += () =>
            //    {
            //    //做要加载的动作
            //    startingWindow.SetTips("等待中1");
            //        Thread.Sleep(1000);
            //        startingWindow.SetTips("等待中2");
            //        Thread.Sleep(1000);
            //        startingWindow.SetTips("等待中3");
            //        Thread.Sleep(1000);
            //    };
            //    startingWindow.exitHandler += () =>
            //    {
            //    //点击退出时 做要退出加载的动作
            //    startingWindow.SetTips("退出加载1");
            //        Thread.Sleep(1000);
            //        startingWindow.SetTips("退出加载2");
            //        Thread.Sleep(1000);
            //        startingWindow.SetTips("退出加载3");
            //        Thread.Sleep(1000);

            //    };

            //    //
            //    startingWindow.ShowDialog();
            //}
        }

        private void button1_Click(object sender, EventArgs e)
        {
             var  rs =  RSAHelper.GetRASKey();
             File.WriteAllText("rsa.key", rs.PrivateKey + "\r\n" + rs.PublicKey);
             MessageBox.Show("生成的秘钥对保存在当前目录下 ras.key 文件中，第一行为PrivateKey，第二行为PublicKey");
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if(MessageBox.Show($"当前选择到期时间为：{dateTimePicker1.Value}\r\n是否继续生成？") ==  DialogResult.OK )
            {
                if (!String.IsNullOrWhiteSpace(textBox1.Text))
                {
                    String[] line = textBox1.Text.Split(new char[] { '/' });

                    textBox2.Clear();
                    textBox2.AppendText(textBox1.Lines[0] + "/");
                    textBox2.AppendText(RSAHelper.EncryptString(line[0], privateKey) + "/");
                    textBox2.AppendText(RSAHelper.EncryptString(dateTimePicker1.Value.ToString(), privateKeyTime) + "/");
                    textBox2.AppendText(RSAHelper.EncryptString(DateTime.Now.ToString(), privateKeyTime));
                }
                else
                {
                    MessageBox.Show("请输入注册码或拖待注册文件到注册码窗口");
                }
            } 
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                AppLicense appLicense = new AppLicense();
                String msg = "";
                DateTime UsePeriod = new DateTime();
                DateTime LastUsedDate = new DateTime();
                String[] line = textBox2.Text.Split(new char[] { '/' });
                if (appLicense.CheckLicense(line[0], line[1], line[2], line[3], ref UsePeriod, ref LastUsedDate, ref msg))
                {
                    MessageBox.Show($"注册码通过检测\r\n授权到期时间为{UsePeriod}\r\n最近使用时间为{LastUsedDate}");
                }
                else
                    MessageBox.Show($"{msg}\r\n授权到期时间为{UsePeriod}\r\n最近使用时间为{LastUsedDate}");
            }
            catch (Exception ex)
            {
                LogHelper.Info("注册码检查",ex);
                MessageBox.Show(ex.Message);
            }
           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrWhiteSpace(textBox1.Text))
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.FileName = "license.dat";
                sfd.Filter = "文本文件(*.dat)|*.dat|所有文件(*.*)|*.*";
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    File.WriteAllText(sfd.FileName, textBox2.Text);
                }
            }
            else
            {
                MessageBox.Show("先生成注册码才可以导出！");
            }
            
        }

        private void textBox1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
                this.textBox1.Cursor = System.Windows.Forms.Cursors.Arrow;  //指定鼠标形状（更好看）
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }

        }

        private void textBox1_DragDrop(object sender, DragEventArgs e)
        {
            string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            textBox1.Text = File.ReadAllText(path);
            this.textBox1.Cursor = System.Windows.Forms.Cursors.IBeam; //还原鼠标形状
        }

        private void textBox2_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
                this.textBox2.Cursor = System.Windows.Forms.Cursors.Arrow;  //指定鼠标形状（更好看）
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void textBox2_DragDrop(object sender, DragEventArgs e)
        {
            string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            textBox2.Text = File.ReadAllText(path);
            this.textBox2.Cursor = System.Windows.Forms.Cursors.IBeam; //还原鼠标形状
        }

        private void button5_Click(object sender, EventArgs e)
        {
            regForm.license.publicKey = publicKey;
            regForm.license.privateKeyTime = privateKeyTime;
            regForm.license.publicKeyTime = publicKeyTime;

            textBox1.Text = regForm.license.GetMachineCode();
            dateTimePicker1.Value = DateTime.Now.AddHours(1);
            ////注册检测
            if (!(regForm.ShowDialog() == DialogResult.OK))
            {
                //程序未注册直接退出
                Close();
                Application.Exit();
                return;
            }
            else
            {
                //启动加载等待
                //StartingWindow startingWindow = new StartingWindow("应用程序名称","公司名称");
                StartingWindow startingWindow = new StartingWindow("AppDemo", "dhsososo@163.com");
                startingWindow.loadingHandler += () =>
                {
                    //做要加载的动作
                    startingWindow.SetTips("等待中1");
                    Thread.Sleep(1000);
                    startingWindow.SetTips("等待中2");
                    Thread.Sleep(1000);
                    startingWindow.SetTips("等待中3");
                    Thread.Sleep(1000);
                };
                startingWindow.exitHandler += () =>
                {
                    //点击退出时 做要退出加载的动作
                    startingWindow.SetTips("退出加载1");
                    Thread.Sleep(1000);
                    startingWindow.SetTips("退出加载2");
                    Thread.Sleep(1000);
                    startingWindow.SetTips("退出加载3");
                    Thread.Sleep(1000);

                };

                //
                startingWindow.ShowDialog();
            }
        }
    }
}
